package com.monitor.commons;

import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;

import java.lang.reflect.Field;
import java.util.HashSet;
import java.util.Set;

/**
 * @author sunke
 * @Date 2017/6/15 16:33
 * @description 对象拷贝
 */

public final class BeanUtils {


    public static String[] getNullPropertyNames(Object source) {
        final BeanWrapper src = new BeanWrapperImpl(source);
        java.beans.PropertyDescriptor[] pds = src.getPropertyDescriptors();

        Set<String> emptyNames = new HashSet<String>();
        for (java.beans.PropertyDescriptor pd : pds) {
            try {
                Object srcValue = src.getPropertyValue(pd.getName());
                if (srcValue == null)
                    emptyNames.add(pd.getName());
            } catch (Exception e) {

            }
        }
        String[] result = new String[emptyNames.size()];
        return emptyNames.toArray(result);
    }


    public static void copyPropertiesIgnoreNull(Object source, Object target) {
        org.springframework.beans.BeanUtils.copyProperties(source, target, getNullPropertyNames(source));
    }

    /**
     * @param obj       待反射的对象
     * @param fieldName 需要赋值的字段(首字母小写驼峰)
     * @param value     需要赋的值
     */
    public static void setPropertyInBean(Object obj, String fieldName, Object value) {
        if (StringUtil.isObjEmpty(obj))
            return;
        Class<? extends Object> classType = obj.getClass();
        Field[] fields;
        String field;
        try {
            while (!Object.class.equals(classType) && classType != null) {
                fields = classType.getDeclaredFields();// 获取当前类所有的属性


                for (Field f : fields) {
                    f.setAccessible(true);// 设置允许获得的权限
                    field = f.toString().substring(
                            f.toString().lastIndexOf(".") + 1); // 取属性名称
                    if (field.equals(fieldName)) {
                        f.set(obj, value);
                        return;
                    }
                }


                classType = classType.getSuperclass();// 向上遍历父类

            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }
}